import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    products: [
      { id: 1, name: '水果手机', price: 59000 },
      { id: 2, name: '外星人鼠标', price: 25000 },
      { id: 3, name: '美利坚键盘', price: 12000 }
    ],
    cart: []
  },
  mutations: {
    ADD_TO_CART(state, product) {
      const item = state.cart.find(item => item.id === product.id);
      if (item) {
        item.quantity++;
      } else {
        state.cart.push({ ...product, quantity: 1 });
      }
    },
    INCREASE_QUANTITY(state, productId) {
      const item = state.cart.find(item => item.id === productId);
      if (item) {
        item.quantity++;
      }
    },
    DECREASE_QUANTITY(state, productId) {
      const item = state.cart.find(item => item.id === productId);
      if (item && item.quantity > 1) {
        item.quantity--;
      } else if (item) {
        state.cart.splice(state.cart.indexOf(item), 1);
      }
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('ADD_TO_CART', product);
    },
    increaseQuantity({ commit }, productId) {
      commit('INCREASE_QUANTITY', productId);
    },
    decreaseQuantity({ commit }, productId) {
      commit('DECREASE_QUANTITY', productId);
    }
  },
  getters: {
    totalPrice: state => {
      return state.cart.reduce((total, item) => {
        return total + item.price * item.quantity;
      }, 0);
    }
  }
});